import React, { Dispatch, SetStateAction } from "react"
import useUnmountedRef from "./useUnmountedRef"

function useSafeState<S>(
  initialState: S | (() => S)
): [S, Dispatch<SetStateAction<S>>]

function useSafeState<S = undefined>(): [
  S | undefined,
  Dispatch<SetStateAction<S | undefined>>
]

/**
 * 用法与 React.useState 完全一样，但是在组件卸载后异步回调内的 setState 不再执行，避免因组件卸载后更新状态而导致的内存泄漏
 * @param initialState
 */
function useSafeState(initialState?) {
  const unmountedRef = useUnmountedRef()
  const [state, setState] = React.useState(initialState)
  const setCurrentState = React.useCallback((currentState) => {
    /** 如果组件已经卸载则不再更新 state */
    if (unmountedRef.current) return
    setState(currentState)
  }, [])

  return [state, setCurrentState] as const
}

export default useSafeState
